package cn.dapeng.features;

import cn.dapeng.util.SleepingUtil;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;


/**
 * ReentrantLock高级用法：
 * 打断当前的线程，使用interrupt方法
 * <p>
 * 线程t1启动后，拿到锁，并且睡眠，永远不会释放锁
 * <p>
 * 线程t2启动后，由于锁一直被t1持有，所有自己打断自己
 */
public class ReentrantLock_T04 {


    public static void main(String[] args) throws Exception {

        ReentrantLock lock = new ReentrantLock();

        Thread t1 = new Thread(() -> {
            lock.lock();
            System.out.println("t1 started");
            SleepingUtil.sleep(Integer.MAX_VALUE, TimeUnit.SECONDS);
            lock.unlock();
        }, "t1");

        t1.start();

        SleepingUtil.sleep(1, TimeUnit.SECONDS);
        Thread t2 = new Thread(() -> {
            try {
                lock.lockInterruptibly();

                System.out.println("t2 started");
            } catch (InterruptedException e) {
                System.err.println("t2 interrupted");
            } finally {
                if (lock.isHeldByCurrentThread()) {
                    lock.unlock();
                }
            }

        }, "t2");

        t2.start();

        SleepingUtil.sleep(10, TimeUnit.SECONDS);

        t2.interrupt();
    }
}
